const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');

// 定义Package模型
const Package = sequelize.define('Package', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    unique: true,
    comment: 'npm包名称'
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: 'npm包描述（英文）'
  },
  description_zh: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: 'npm包描述（中文）'
  },
  descriptionCN: {
    type: DataTypes.VIRTUAL,
    get() {
      return this.getDataValue('description_zh');
    },
    set(value) {
      this.setDataValue('description_zh', value);
    }
  },
  latestVersion: {
    type: DataTypes.VIRTUAL,
    get() {
      return this.getDataValue('version');
    },
    set(value) {
      this.setDataValue('version', value);
    }
  },
  lastSyncAt: {
    type: DataTypes.VIRTUAL,
    get() {
      return this.getDataValue('last_synced_at');
    },
    set(value) {
      this.setDataValue('last_synced_at', value);
    }
  },
  author: {
    type: DataTypes.STRING(100),
    allowNull: true,
    comment: '作者'
  },
  version: {
    type: DataTypes.STRING(20),
    allowNull: true,
    comment: '当前版本'
  },
  stars: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: 'GitHub星数'
  },
  downloads: {
    type: DataTypes.BIGINT,
    defaultValue: 0,
    comment: '总下载量'
  },
  score: {
    type: DataTypes.FLOAT,
    defaultValue: 0,
    comment: '评分'
  },
  last_synced_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '最后同步时间'
  },
  npm_url: {
    type: DataTypes.STRING(255),
    allowNull: true,
    comment: 'npm官网地址'
  },
  github_url: {
    type: DataTypes.STRING(255),
    allowNull: true,
    comment: 'GitHub地址'
  },
  is_popular: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    comment: '是否热门'
  }
}, {
  tableName: 'packages',
  indexes: [
    { name: 'idx_downloads', fields: ['downloads'] },
    { name: 'idx_popular', fields: ['is_popular'] }
  ]
});

module.exports = Package;